#' Generate pic
#'
#' This function is pipeline for generation pic of str
#'
#' @import xlsx
#' @param input.dir Input dir which stores fsa files
#' @param output.dir Result dir for stores png files
#' @param sample.list Match file for sample file and sample name
#' @param ... Other params or for future changes
pipeline_str_pic <- function(input.dir, output.dir, ...) {
  given.opts = list(...)
  if (is.null(given.opts$sample.list)) { 
    # 没有sample.list信息的情况，目前还没有确定如何确定样本关系
    # 还要看实验那边如何处理
  } else {
    cat(file = stderr(), paste("parsing", given.opts$sample.list,"\n"))
    xlsx <- read.xlsx(given.opts$sample.list,1)
    sample.name <- as.character(xlsx[[2]])
    names(sample.name) <- as.character(xlsx[[1]])
  }
  # 处理samples.select情况
  if (is.null(given.opts$samples.select)) {
    samplenumber = length(sample.name)/2
    group <- sample_match(sample.name)
  } else {
    select.samples <- unlist(strsplit(given.opts$samples.select,","))
    sample.name.select <- c();
    for (item in select.samples) {
      find.item<-grepl(item, sample.name)
      if(any(find.item)) {
        sample.name.select<-append(sample.name.select,sample.name[find.item])
      }
    }
    sample.name.select.names<-unique(names(sample.name.select))
    sample.name.select<-unique(sample.name.select)
    names(sample.name.select)<-sample.name.select.names
    samplenumber = length(sample.name.select)/2
    group <- sample_match(sample.name.select)
  }
  cat(file = stderr(), paste('Total number is', samplenumber,"\n"))
  # group变量存储了样本的分组信息
  # 一个组一个组的处理
  for (samplename in names(group)) {
    cat(file = stderr(), paste("Analying", samplename, "...\n"))
    tmp <- paste(input.dir, samplename, sep="/") # 未来input.dir换成tmp.dir参数
    if (!file.exists(tmp)) {
      dir.create(tmp, recursive = TRUE)
    }
    fsadir <- paste(input.dir, "fsa", sep="/") # 未来做成参数
    if (group[[samplename]]['m'] != "") {
      mom.fsa.from <- paste(fsadir, group[[samplename]]['m'], sep="/")
      mom.fsa.to <- paste(tmp, paste(samplename, "M.fsa", sep=""), sep="/")
    } else {
      mom.fsa.from <- ""
    }
    if (group[[samplename]]['b'] != "") {
      bab.fsa.from <- paste(fsadir, group[[samplename]]['b'], sep="/")
      bab.fsa.to<- paste(tmp, paste(samplename, ".fsa", sep=""), sep="/")
    } else {
      bab.fsa.from <- ""
    }
    #cat(file = stderr(), paste(mom.fsa,bab.fsa,"\n",sep="-->"))
    if (file.exists(mom.fsa.from) & file.exists(bab.fsa.from)) {
      file.copy(mom.fsa.from, mom.fsa.to, overwrite=TRUE)
      file.copy(bab.fsa.from, bab.fsa.to, overwrite=TRUE)
      # 开始一个一个生成图片
      output <- paste(output.dir,samplename, sep="/")
      if (!file.exists(output)) {
        dir.create(output, recursive = TRUE)
      }
      data <- storing.inds(tmp)
      score.easy(my.inds=data,panel=c(70,490),ladder=template.ladder,cols=1, 
                plotfile = paste(output, paste(samplename,".B.png",sep=""),sep="/"),
                ladd.init.thresh = given.opts$ladd.init.thresh)
      score.easy(my.inds=data,panel=c(70,490),ladder=template.ladder,cols=2,
                plotfile = paste(output, paste(samplename,".G.png",sep=""),sep="/"),
                ladd.init.thresh = given.opts$ladd.init.thresh)
      score.easy(my.inds=data,panel=c(70,490),ladder=template.ladder,cols=3,
                plotfile = paste(output, paste(samplename,".Y.png",sep=""),sep="/"),
                ladd.init.thresh = given.opts$ladd.init.thresh)
      score.easy(my.inds=data,panel=c(70,490),ladder=template.ladder,cols=4,
                plotfile = paste(output, paste(samplename,".R.png",sep=""),sep="/"),
                ladd.init.thresh = given.opts$ladd.init.thresh)
      #str(data)
    } else {
      cat(file = stderr(), paste(samplename,"hasn't fsa data!\n"))
    }
    # 删除临时文件夹
    unlink(tmp, force = TRUE, recursive = TRUE)
  }
  # 测试data
  #str(template.ladder) # OK
  #str(xlsx)
  return(0)
}

sample_match <- function(sample.name) {
  group <- list()
  for (sample in sample.name) {
    sample1 <- gsub('^ +', '', sample, perl=TRUE)
    flag <- grepl('M$', sample1, perl=TRUE)
    if (flag) {
      key <- gsub('M$', '', sample1, perl=TRUE)
      if (is.null(group[[key]])) {
        group[[key]] <- c("", names(sample.name)[sample.name == sample])
        names(group[[key]]) <- c('b','m')
      } else {
        group[[key]][2] <- names(sample.name)[sample.name == sample]
      }
    } else {
      key <- sample1
      if (!is.null(group[[key]])) {
        group[[key]][1] <- names(sample.name)[sample.name == sample]
      } else {
        group[[key]] <- c(names(sample.name)[sample.name == sample], "");
        names(group[[key]]) <- c('b','m')
      }
    }
  }
  return(group)
}
